package services

import (
	"errors"
	"gorm.io/gorm"
	"mishop/models"
	"mishop/utils"
)

type IAddressService interface {
	FindByID(addressId uint) (*models.Address, error)
	FindByUserID(page, rows int, userId uint) (*models.Pages, error)
	Create(c *models.Address) (*models.Address, error)
	Update(c *models.Address) (*models.Address, error)
	Delete(addressId int) error
}
type AddressService struct {
	model models.IAddress
}

func (p *AddressService) Delete(addressID int) error {
	return p.model.Delete(addressID)
}

func (p *AddressService) Update(c *models.Address) (*models.Address, error) {
	_, err := p.model.FindByID(c.ID)
	if err != nil && err == gorm.ErrRecordNotFound {
		return nil, errors.New("地址未找到")
	}
	return p.model.Update(c)
}

func (p *AddressService) Create(c *models.Address) (*models.Address, error) {
	return p.model.Create(c)
}
func (p *AddressService) FindByID(addressId uint) (*models.Address, error) {
	return p.model.FindByID(addressId)
}

func (p *AddressService) FindByUserID(page, rows int, userId uint) (*models.Pages, error) {
	page, rows = utils.ProcessPagesEntity(page, rows)
	return p.model.FindByUserID(page, rows, userId)
}

func NewAddressService(model models.IAddress) IAddressService {
	return &AddressService{model: model}
}
